//
//  TMNetWorkTools.swift
//  2.swift网络请求单例类封装
//
//  Created by 汤米 on 16/4/19.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit
import AFNetworking
class TMNetWorkTools: AFHTTPSessionManager {

    // MARK: -  网络访问单例
    // MARK: -  方式1
    static let sharedTool: TMNetWorkTools = {
        let tool = TMNetWorkTools()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    


    // MARK: -  封装网络请求
    func request(method: String, urlString: String, param: AnyObject?, callBack:(response: AnyObject?, error: NSError?) -> ()) {
        
        if method == "GET" {
            
            self.GET(urlString, parameters: param, progress: nil, success: { (_, responseObject) -> Void in
                callBack(response: responseObject, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
                    
            })

            
        }else {
            
            self.POST(urlString, parameters: param, progress: nil, success: { (_, responseObject) -> Void in
                callBack(response: responseObject, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)

            })
        }
    }
}


// MARK: -  请求微博首页数据
extension TMNetWorkTools {
    
    func loadHomeData(accessToken:String, since_id: Int64, max_id: Int64, callback:(response: AnyObject?, error: NSError?)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let param = [
            "access_token": accessToken,
            "since_id": "\(since_id)",
            "max_id": "\(max_id)"
        ]
        
        request("GET", urlString: urlString, param: param) { (response, error) -> () in
            
            callback(response: response, error: error)
        }
        
    }
}
